# -*- coding: utf-8 -*-
import os
import random
import time
from threading import Thread


class FileHelper(object):
    """
    文件相关处理类
    """

    def __init__(self) -> None:
        super().__init__()
        self.temp_str = ''
        self.temp_count = 0

    def gen_sql(self, data_file, target='./', template='{}', split=','):
        try:
            encoding = 'UTF-8'
            with open(data_file, 'r', encoding=encoding) as sf:
                if split:
                    for line in sf:
                        render_data = line.replace('\n', '').split(split)
                        self.temp_count += 1
                        Thread(target=self.__gen_template_str, args=(template, render_data,)).start()
                else:
                    for line in sf:
                        line = line.replace('\n','')
                        print('line content', line)
                        self.temp_count += 1
                        Thread(target=self.__gen_template_str, args=(template, line,)).start()

            while self.temp_count != 0:
                time.sleep(1)

            output_name = 'output_%d.sql' % random.randint(1, 100)
            target = os.path.join(target, output_name)
            with open(target, 'w', encoding=encoding) as of:
                of.write(self.temp_str)

        except EOFError as e:
            print('gen sql error', data_file, e)

        return target

    def __gen_template_str(self, template, *render_data):
        self.temp_str += template.format(*render_data)
        self.temp_count -= 1
